package com.landiao.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.landiao.common.Constant;
import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.utils.CodecUtils;
import com.landiao.common.utils.DateUtil;
import com.landiao.entities.Coupon;
import com.landiao.entities.CouponReceive;
import com.landiao.entities.Vip;
import com.landiao.mapper.CouponMapper;
import com.landiao.mapper.CouponReceiveMapper;

@Service
public class CouponReceiveService extends BaseService<CouponReceive, String> {

	@Autowired
	private CouponMapper couponMapper;
	
	@Override
	protected CouponReceiveMapper getBaseMapper() {
		// TODO Auto-generated method stub
		return (CouponReceiveMapper)baseMapper;
	}
	
	public List<CouponReceive> getListByVipId(String vipId){
		CouponReceive cr = new CouponReceive();
		cr.setVipId(vipId);
		return this.baseMapper.queryByPage(cr,null);
	}
	
	public CouponReceive getByVipIdAndCouponId(String vipId,String couponId){
		return this.getBaseMapper().selectByVipIdAndCouponId(vipId, couponId);
	}
	
	public synchronized ResultMsg receiveCoupon(Vip vip,String couponId){
		Coupon coupon = this.couponMapper.selectByPrimaryKey(couponId);
		if(coupon==null||coupon.getState().equals("10X")){
			return ResultMsgFactory.fail("未找到卡券信息");
		}
		Date date = DateUtil.getDateAfter(new Date(), 1);
		if(coupon.getEndDate().before(date)){
			return ResultMsgFactory.fail("卡券已过期");
		}
		if(coupon.getSurplusNum()<=0){
			return ResultMsgFactory.fail("您来晚了，卡卷已被领完");
		}
		coupon.setSurplusNum(coupon.getSurplusNum()-1);
		this.couponMapper.updateByPrimaryKey(coupon);
		
		CouponReceive cr = new CouponReceive();
		cr.setCouponReceiveId(CodecUtils.getUUID());
		cr.setCompId(coupon.getCompId());
		cr.setCouponId(couponId);
		cr.setVipId(vip.getVipId());
		cr.setEndDate(coupon.getEndDate());
		cr.setIsOutdate(coupon.getIsOutdate());
		cr.setIsUsed(Constant.STATE_NORMAL);
		cr.setStatedate(new Date());
		this.getBaseMapper().insert(cr);
		return ResultMsgFactory.success("恭喜您，领取成功");
	}
	
	public List<Coupon> getValidCoupon(String vipId,String shopId,List<String> serviceItems){
		return this.couponMapper.selectValidCoupon(vipId, shopId, serviceItems);
	}
	
	public CouponReceive getValidByVipIdAndServiceItemId(String vipId,String serviceItemId){
		return this.getBaseMapper().selectValidByVipIdAndServiceItemId(vipId, serviceItemId);
	}
}
